import { defineComponent, reactive, Ref, ref, toRefs } from 'vue'
import { NForm, NFormItem, NModal, NCheckbox, NCheckboxGroup } from 'naive-ui'
import { Response } from '@/service/modules/common/types'
import { modUserPrivilegeReq } from '@/service/modules/data-manage'

const ModUserPrivilegeModal = defineComponent({
  name: 'ModUserPrivilegeModal',
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    userId: {
      type: Number,
      required: true
    },
    tableId: {
      type: Number,
      required: true
    },
    privileges: {
      type: Array<string>,
      required: true
    }
  },
  emits: ['modalShowChange', 'refreshList'],
  setup() {
    const state = reactive({
      positiveButtonDisabled: ref(false)
    })
    const privilegesValues: Ref<string[]> = ref([])

    return {
      ...toRefs(state),
      privilegesValues
    }
  },
  updated() {
    this.privilegesValues = this.privileges
  },
  methods: {
    async onPositiveClick() {
      //提交添加用户权限请求
      this.positiveButtonDisabled = true
      const res: Response<any> = await modUserPrivilegeReq({
        userId: this.userId,
        tableId: this.tableId,
        privileges: this.privilegesValues + ''
      }).catch(() => {
        this.positiveButtonDisabled = false
      })
      if (res.resp_code === 0) {
        this.initData()
        this.$emit('modalShowChange', false)
        this.$emit('refreshList')
        this.positiveButtonDisabled = false
      } else {
        this.positiveButtonDisabled = false
      }
    },
    onNegativeClick() {
      this.initData()
      this.$emit('modalShowChange', false)
    },
    initData() {
      this.privilegesValues = []
    }
  },
  render() {
    return (
      <NModal
        show={this.showModal}
        mask-closable={false}
        style='width: 400px'
        title={window.$t('dataManage.modPrivilege')}
        bordered={false}
        size='huge'
        preset='dialog'
        positive-text={window.$t('dialog.positiveText')}
        negative-text={window.$t('dialog.negativeText')}
        onPositiveClick={this.onPositiveClick}
        onNegativeClick={this.onNegativeClick}
        onClose={this.onNegativeClick}
      >
        <NForm
          label-placement='top'
          require-mark-placement='right-hanging'
          label-width='auto'
        >
          <NFormItem path='privileges'>
            <NCheckboxGroup v-model:value={this.privilegesValues}>
              <NCheckbox value='SELECT' label='SELECT' />
              <NCheckbox value='INSERT' label='INSERT' />
              <NCheckbox value='UPDATE' label='UPDATE' />
              <NCheckbox value='DELETE' label='DELETE' />
            </NCheckboxGroup>
          </NFormItem>
        </NForm>
      </NModal>
    )
  }
})

export default ModUserPrivilegeModal
